﻿using System;

namespace FindDihotTDD
{
    public class SearchDichotomy
    {
        public int n;
        public int[] arr;

        public bool isEmpty()
        {
            return true;
        }

        public void createArray(int p)
        {
            arr = new int[p];
            Random rand = new Random();
            for (int i = 0; i < p; i++)
            {
                arr[i] = rand.Next(-1000, 1000);
            }
        }

        public void setN(int p)
        {
            Random rand = new Random();
            n = rand.Next(p);
        }

        //public int[] sortArray(int[] mas)
        //{
        //    int c = 0;
        //    for (int i = mas.Length - 1; i > 0; i--)
        //    {
        //        for (int j = 0; j < i; j++)
        //        {
        //            if (mas[j] > mas[j + 1])
        //            {
        //                c = mas[j];
        //                mas[j] = mas[j + 1];
        //                mas[j + 1] = c;
        //            }
        //        }
        //    }
        //    return mas;
        //}

        public int dichotSearch(int[] mas, int x)
        {
            Array.Sort(mas);
            int first = 0;
            int last = mas.Length;
            int mid;

            if (mas.Length == 0)
            {
                throw new Exception();
            }
            if (mas.Length == 1)
            {
                if (mas[0] == x)
                    return 0;
                else return -1;
            }
            else if (mas[0] > x)
            {
                return -1;
            }
            else if (mas[mas.Length - 1] < x)
            {
                return -1;
            }

            while (first < last)
            {
                mid = first + (last - first) / 2;

                if (x <= mas[mid])
                {
                    last = mid;
                }
                else
                {
                    first = mid + 1;
                }
            }

            if (mas[last] == x)
            {
                return last;
            }
            else
            {
                return -1;
            }
        }
    }
}
